package com.exercise.rpc.common.registry.impl;/**
 * Created by kete on 2018-10-26.
 */

import com.exercise.rpc.client.ConnectManage;
import com.exercise.rpc.common.registry.Constants;
import com.exercise.rpc.common.registry.ServiceDiscovery;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 作者：kete
 * 创建时间：2018-10-26 16:47
 * 功能描述：
 * 版本：
 */
public class ZookeeperDiscovery implements ServiceDiscovery {
    private static final Logger logger = LoggerFactory.getLogger(ZookeeperDiscovery.class);

    private CountDownLatch latch = new CountDownLatch(1);

    private String zookAddress;

    private ZooKeeper zooKeeper;

    private volatile List<String> dataList = new ArrayList<>();


    public ZookeeperDiscovery(String zookAddress) {
        this.zookAddress = zookAddress;

        zooKeeper = connectServer();

        if(null!=zooKeeper)
            watchNode(zooKeeper);

    }


    private void watchNode(final ZooKeeper zk) {
        try {
            List<String> nodeList = zk.getChildren(Constants.ZK_REGISTRY_PATH, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getType() == Event.EventType.NodeChildrenChanged) {
                        watchNode(zk);
                    }
                }
            });
            List<String> dataList = new ArrayList<>();
            for (String node : nodeList) {
                byte[] bytes = zk.getData(Constants.ZK_REGISTRY_PATH + "/" + node, false, null);
                dataList.add(new String(bytes));
            }
            logger.debug("node data: {}", dataList);
            this.dataList = dataList;

            logger.debug("Service discovery triggered updating connected server node.");
            ConnectManage.me().updateConnectedServer(dataList);
        } catch (KeeperException | InterruptedException e) {
            logger.error("", e);
        }
    }

    private ZooKeeper connectServer(){
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(zookAddress, Constants.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });

            latch.await();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return zooKeeper;

    }

    @Override
    public String discover() {
        String data = null;
        int size = dataList.size();
        if (size > 0) {
            if (size == 1) {
                data = dataList.get(0);
                logger.debug("using only data: {}", data);
            } else {
                data = dataList.get(ThreadLocalRandom.current().nextInt(size));
                logger.debug("using random data: {}", data);
            }
        }

        dataList.forEach(str->System.out.printf("data:"+str));
        return data;
    }

    @Override
    public void stop(){
        if(zooKeeper!=null){
            try {
                zooKeeper.close();
            } catch (InterruptedException e) {
                logger.error("", e);
            }
        }
    }
}
